﻿using System;
using System.Collections.Generic;
using ZyGames.DZPocker.Model;
using ZyGames.Framework.Cache.Generic;
using ZyGames.Framework.Game.Cache;
using ZyGames.Framework.Game.Context;
using ZyGames.Framework.Game.Contract;
using ZyGames.Framework.Game.Contract.Action;
using ZyGames.Framework.Game.Lang;
using ZyGames.Framework.Game.Service;
using System.Linq;
using ZyGames.DZPocker.Bll.Logic;
using ZyGames.DZPocker.Script;
using ZyGames.Framework.Net;
using ZyGames.Framework.Common.Serialization;
using System.Threading;
using ZyGames.DZPocker.Tools;

namespace ZyGames.DZPocker.Script.CsScript.Action
{
	/// <summary>
	/// 主动非广播取消购买保险
	/// </summary>
	public class Action30028 : BaseAction
	{
		private int tableId;
		private int userId;
		private int posId;
		
		private bool result = false;

		private TableData _currentTable;
		private GameUser _currentGameUser;

		public Action30028(HttpGet actionGetter)
			: base((short)ActionType.DZCancelInsurance, actionGetter)
		{
		}
		public override bool GetUrlElement()
		{
			if (httpGet.GetInt("TableId", ref tableId) &&
				httpGet.GetInt("UserId", ref userId) &&
				httpGet.GetInt("PosId", ref posId))
			{
				return true;
			}
			return false;
		}

		public override bool TakeAction()
		{
			_currentTable = GameRoom.Current.GetTableData(tableId);
			if (_currentTable == null)
			{
				Tool.WriteWarmingLine("消息30028获得房间不存在");
				return false;
			}
			if (posId > _currentTable.PlayerNum)
			{
				Tool.WriteWarmingLine("消息30028座位号不合法");
				return false;
			}
			var pos = _currentTable.Positions[posId - 1];
			if (pos == null)
			{
				Tool.WriteWarmingLine("消息30028座位号不存在");
				return false;
			}
			_currentGameUser = GameTable.Current.GetUser(userId);
			if (_currentGameUser == null)
			{
				Tool.WriteWarmingLine("消息30028玩家不存在");
				return false;
			}
			//下发之后在进行下一回合
			if (_currentTable.State == TableState.Insurance)
			{
				Tool.WriteErrorLine("30028协议里面取消定时器");
				_currentTable.StopTimer();
			}

			result = true;
			return true;
		}

		public void ThreadFunc()
		{
			Tool.WriteErrorLine("回合结束操作，延时0.5s");
			System.Threading.Thread.Sleep(500);

			//GameTable.Current.RoundInsuranceCanGoToNext(_currentTable);
		}

		public override void BuildPacket()
		{
			this.PushIntoStack(this.result);
			this.PushIntoStack(this.tableId);
			//开启新的线程来避免阻塞
			Thread t1 = new Thread(new ThreadStart(ThreadFunc));
			t1.IsBackground = true;
			t1.Start();
		}
	}
}
